/*
 * Copyright (C) 2010 Moduad Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.rytong.tools.androidpn.client;

import java.util.List;
import java.util.Random;

import com.rytong.tools.utils.LPToastUtil;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

/**
 * This class is to notify the user of messages with NotificationManager.
 * 
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class Notifier {

    private static final String LOGTAG = LogUtil.makeLogTag(Notifier.class);

    private static final Random random = new Random(System.currentTimeMillis());

    private Context context_;

    private SharedPreferences sharedPrefs;

    private NotificationManager notificationManager;

    public Notifier(Context context) {
        this.context_ = context;
        this.sharedPrefs = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
        this.notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void notify(String notificationId, String apiKey, String title, String message, String uri) {
        Log.d(LOGTAG, "notify()...");

        Log.d(LOGTAG, "notificationId=" + notificationId);
        Log.d(LOGTAG, "notificationApiKey=" + apiKey);
        Log.d(LOGTAG, "notificationTitle=" + title);
        Log.d(LOGTAG, "notificationMessage=" + message);
        Log.d(LOGTAG, "notificationUri=" + uri);

        if (isNotificationEnabled()) {
            // Show the toast
            if (isNotificationToastEnabled()) {
                LPToastUtil.getInstance().getToast(message, context_);
            }

            Notification.Builder builder = new Notification.Builder(context_);

            Intent intent = new Intent();

            intent.putExtra(Constants.NOTIFICATION_ID, notificationId);
            intent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
            intent.putExtra(Constants.NOTIFICATION_TITLE, title);
            intent.putExtra(Constants.NOTIFICATION_MESSAGE, message);
            intent.putExtra(Constants.NOTIFICATION_URI, uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);// ���ú󲻻������activity
            PendingIntent contentIntent = PendingIntent.getActivity(context_, 0, intent, 0);

            builder.setContentIntent(contentIntent);

            // Notification
//            Notification notification = new Notification();
            Notification notification = builder.build();
            notification.icon = getNotificationIcon();
            notification.defaults = Notification.DEFAULT_LIGHTS;
            if (isNotificationSoundEnabled()) {
                notification.defaults |= Notification.DEFAULT_SOUND;
            }
            if (isNotificationVibrateEnabled()) {
                notification.defaults |= Notification.DEFAULT_VIBRATE;
            }
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.when = System.currentTimeMillis();
            notification.tickerText = message;

            /*try {// add by du.hu ��Ϣ������ʾ
                Intent intent = new Intent();

                intent.putExtra(Constants.NOTIFICATION_ID, notificationId);
                intent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
                intent.putExtra(Constants.NOTIFICATION_TITLE, title);
                intent.putExtra(Constants.NOTIFICATION_MESSAGE, message);
                intent.putExtra(Constants.NOTIFICATION_URI, uri);
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);// ���ú󲻻������activity
                PendingIntent contentIntent = PendingIntent.getActivity(context_, 0, intent, 0);
                notification.setLatestEventInfo(context_, title, message, contentIntent);
            } catch (Exception e) {
                e.printStackTrace();
            }*/
            notificationManager.notify(random.nextInt(), notification);

        } else {
            Log.w(LOGTAG, "Notificaitons disabled.");
        }
    }

    private int getNotificationIcon() {
        return sharedPrefs.getInt(Constants.NOTIFICATION_ICON, 0);
    }

    private boolean isNotificationEnabled() {
        return sharedPrefs.getBoolean(Constants.SETTINGS_NOTIFICATION_ENABLED, true);
    }

    private boolean isNotificationSoundEnabled() {
        return sharedPrefs.getBoolean(Constants.SETTINGS_SOUND_ENABLED, true);
    }

    private boolean isNotificationVibrateEnabled() {
        return sharedPrefs.getBoolean(Constants.SETTINGS_VIBRATE_ENABLED, true);
    }

    private boolean isNotificationToastEnabled() {
        return sharedPrefs.getBoolean(Constants.SETTINGS_TOAST_ENABLED, false);
    }

    private boolean isTopActivity() {
        ActivityManager mActivityManager = (ActivityManager) context_.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasksInfo = mActivityManager.getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            // 应用程序位于堆栈的顶层
            if ("com.rytong.ebank".equals(tasksInfo.get(0).topActivity.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    // public boolean isServiceStarted(Context context,String PackageName) {
    // boolean isStarted =false;
    // try {
    // ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
    // int intGetTastCounter = 1000;
    // List<ActivityManager.RunningServiceInfo> mRunningService =
    // mActivityManager.getRunningServices(intGetTastCounter );
    // for (ActivityManager.RunningServiceInfo amService : mRunningService) {
    // if(0 == amService.service.getPackageName().compareTo(PackageName)) {
    // isStarted = true;
    // break;
    // }
    // }
    // } catch(SecurityException e) {
    // e.printStackTrace();
    // }
    // return isStarted;
    // }
}
